package my.http;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.asyncsql.MySQLClient;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.SQLClient;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.templ.FreeMarkerTemplateEngine;

/**
 * @author fengbo
 * @version 1.0.0
 * @date 2018/11/18 14:29
 * @since JDK 1.8
 */
public class VertxServer extends AbstractVerticle {

    private static final Logger log = LoggerFactory.getLogger(VertxServer.class);
    private final FreeMarkerTemplateEngine templateEngine = FreeMarkerTemplateEngine.create();

    @Override
    public void start() throws Exception {
        JsonObject config = new JsonObject()
                .put("host", "127.0.0.1")
                .put("port", 3306)
                .put("username", "root")
                .put("password", "root")
                .put("database", "seckill")
                .put("charset", "utf8");
        SQLClient client = MySQLClient.createShared(vertx, config, "MySQLPool");

        Router router = Router.router(vertx);
        router.route().handler(BodyHandler.create());

        router.get("/get/:id").handler(req ->
                req.response().end("Hello World!" + req.request().getParam("id") + "\n"));
        router.get("/getAll").handler(req ->
            client.getConnection(res -> {
                if (res.succeeded()) {
                    res.result().query("select * from seckill", res2 -> {
                        ResultSet rs = res2.result();
                        req.response().putHeader("context-type", "application/json")
                                .end(Json.encode(rs.getResults()));
                    }).close();
                } else {
                    log.error("error");
                }
            }));
        router.put("/add").handler(this::add);

        vertx.createHttpServer()
                .requestHandler(router::accept)
                .listen(8080);
    }

    private void add(RoutingContext routingContext) {
        HttpServerResponse response = routingContext.response();
        JsonObject product = routingContext.getBodyAsJson();
        log.info(product.encode());
        response.putHeader(HttpHeaders.CONTENT_TYPE, "application/json").end(product.encode());
    }

    public static void main(String[] args) {
        Vertx.vertx().deployVerticle(new VertxServer());
    }
}
